<?php
/**
 * Created by PhpStorm.
 * User: suruixiang
 * Date: 2017/9/29
 * Time: 下午4:19
 */
namespace app\admin\model;

use think\Model;

class Admin extends Model
{
    /**
     * 根据单字段获取信息
     * @param $user_name
     * @param string $fields
     * @return object
     */
    public function getInfoByField($field_name, $field_value, $fields = '*')
    {
        return $this->where($field_name, $field_value)->field($fields)->find();
    }

    /**
     * 更新用户登录时间和IP
     * @param $user_id
     * @return boole
     */
    public function upTimeIp($user_id)
    {
        return $this->where('id', $user_id)->update([
            'last_time' => time(),
            'last_ip'   => getIPaddress()
        ]);
    }

    /**
     * 新增和编辑用户
     * @param array $user_data
     * @param int $user_id
     * @return int
     */
    public function userEdit(array $user_data, $user_id = 0)
    {
        $user_data = array_filter($user_data);
        if (!empty($user_data['password'])) {
            $user_data['password'] = md5($user_data['password']);
        }
        if (!$user_id && !$user_data['password']) {
            $user_data['password'] = md5('tppassword');
        }
        if (!$user_id) {
            $user_data['create_time'] = time();
            return $this->insertGetId($user_data);
        } else {
            return $this->where('id', $user_id)->update($user_data);
        }
    }

    /**
     * 获取用户列表
     * @return array
     */
    public function getAllLists()
    {
        $status = [
            1 => '正常',
            2 => '停用'
        ];
        $lists = $this->order('id desc')->select();
        $lists_arrsy = [];
        foreach ($lists as $li){
            $lists_arrsy[] = [
                'id'          => $li->id,
                'user_name'   => $li->user_name,
                'create_time' => $li->create_time,
                'status'      => $status[$li->status],
                'last_time'   => $li->last_time ? date('Y-m-d H:i:s', $li->last_time) : '',
                'last_ip'     => $li->last_ip,
                'status_code' => $li->status
            ];
        }
        return $lists_arrsy;
    }

    /**
     * 删除用户
     * @param $user_id
     * @return int
     */
    public function userDel($user_id)
    {
        return $this->where('id', $user_id)->delete();
    }

    /**
     * 更改用户状态
     * @param $user_id
     * @param int $status
     * @return int 影响数据的条数
     */
    public function userUpStatus($user_id)
    {
        $user = $this->getInfoByField('id', $user_id, 'status');
        $status = $user['status'] == 1 ? 2 : 1;
        return $this->where('id', $user_id)->update([
            'status' => $status
        ]);
    }
}